<template>
  <PageWrapper v-loading="loadingRef" contentFullHeight fixedHeight dense>
    <AdVxeTable @register="registerTable">
      <template #tools>
        <Authority :value="'Root.Admin.Identity.Organization.Create'">
          <a-button type="primary" @click="handleCreate">
            <Icon icon="ant-design:plus-circle-outlined" />{{ t('common.addText') }}
          </a-button>
        </Authority>
        <a-button type="primary" @click="expandAll">
          <Icon icon="bi:arrows-expand" />{{ t('common.expandAll') }}
        </a-button>
        <a-button type="primary" @click="collapseAll">
          <Icon icon="bi:arrows-collapse" />{{ t('common.collapseAll') }}
        </a-button>
      </template>

      <template #actionCol="{ row }">
        <TableAction
          outside
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: t('common.delText'),
              auth: 'Root.Admin.Identity.Organization.Delete', // 权限控制
              ifShow: (_action) => {
                return row?.IsSystem !== true; // 根据业务控制是否显示: 是否可删除的数据权限状态
              },
              popConfirm: {
                title: t('common.delConfirmText'),
                placement: 'left',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
          :dropDownActions="[
            {
              icon: 'clarity:details-line',
              label: t('common.detailText'),
              onClick: handleDetail.bind(null, row),
            },
            {
              icon: 'clarity:note-edit-line',
              label: t('common.editText'),
              auth: 'Root.Admin.Identity.Organization.Update', // 权限控制
              onClick: handleEdit.bind(null, row),
            },
            {
              icon: 'la:user-cog',
              label: t('routes.system.identity.user.title'),
              auth: ['Root.Admin.Identity.User.ReadOrganizationUsers'], // 权限控制
              onClick: handleSetUsersModalOpen.bind(null, row),
            },
            {
              icon: 'carbon:user-role',
              label: t('routes.system.identity.role.title'),
              auth: ['Root.Admin.Identity.Role.ReadOrganizationRoles'], // 权限控制
              onClick: handleSetRolesModalOpen.bind(null, row),
            },
          ]"
        />
      </template>
    </AdVxeTable>

    <OrganizationDetailModal
      @register="registerDetailFormModal"
      :afterSubmitFunc="handleAfterDetailSubmit"
    />
    <OrganizationUserModal
      @register="registerSetUsersModal"
      :title="t('routes.system.identity.user.title')"
      :search="true"
      :closeFunc="handleSetUsersModalClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.User.SetOrganizations'"
      :okFunc="handleSetUsersModalOk"
      width="65%"
    />
    <OrganizationRoleModal
      @register="registerSetRolesModal"
      :title="t('routes.system.identity.role.title')"
      :search="true"
      :closeFunc="handleSetRolesModalClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.Role.SetOrganizations'"
      :okFunc="handleSetRolesModalOk"
      width="65%"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { Authority } from '@/components/Authority';
  import { AdVxeTable, useAdVxeTable, TableAction } from '@/components/AdVxeTable';
  import { PageWrapper } from '@/components/Page';
  import { useMessage } from '@/hooks/web/useMessage';
  import Icon from '@/components/Icon/Icon.vue';

  import {
    readOrganizationTreeNodes,
    deleteOrganizations,
    setOrganizationUsers,
    setOrganizationRoles,
  } from '@/api/identity/admin/organization';
  import { UserOrganizationNode } from '@/api/identity/admin/user/model';
  import { readOrganizationUsers } from '@/api/identity/admin/user';
  import { RoleOrganizationNode } from '@/api/identity/admin/role/model';
  import { readOrganizationRoles } from '@/api/identity/admin/role';

  import { AjaxResult } from '@/api/model';

  import { useModal } from '@/components/AdVxeModal';
  import { FormModeEnum } from '@/enums/formEnum';

  import OrganizationDetailModal from './OrganizationDetailModal.vue';

  import { columns } from './organization.data';

  import OrgUserTransferModal from './OrgUserTransferModal.vue';
  import OrgRoleTransferModal from './OrgRoleTransferModal.vue';

  const OrganizationUserModal = OrgUserTransferModal;
  const OrganizationRoleModal = OrgRoleTransferModal;

  defineOptions({ name: 'OrganizationPage' });

  const { t } = useI18n();
  const { createMessage } = useMessage();

  const loadingRef = ref(false);

  const [registerTable, { getTable, reload }] = useAdVxeTable({
    id: 'system-organization-page-table',
    // 表标题呈现器
    title: t('routes.system.identity.organization.organizationList'),
    // 表格数据接口请求对象
    api: readOrganizationTreeNodes,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'identity_organization_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('routes.system.identity.organization.title'),
    },
    // 表单列信息 AdColumn[]
    columns,
    treeConfig: {
      // transform: true,
      // rowField: 'Id',
      // parentField: 'ParentId',
      childrenField: 'Items',
    },
    // 斑马纹
    stripe: false,
    // 使用搜索表单
    searchForm: true,
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: false,
    //分页信息配置，为 false 不显示分页
    pagerConfig: { currentPage: 1, pageSize: 999999999, layouts: [], autoHidden: true },
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  function expandAll() {
    const $table = getTable();
    if ($table) {
      $table.setAllTreeExpand(true);
    }
  }
  function collapseAll() {
    const $table = getTable();
    if ($table) {
      $table.clearTreeExpand();
    }
  }

  const [registerDetailFormModal, detailFormModalMethods] = useModal();

  /** 处理新增 */
  async function handleCreate() {
    //TODO:详情表单的弹窗
    detailFormModalMethods.openModal(true, {
      formMode: FormModeEnum.Add,
      record: null,
    });
  }

  /** 处理查看详情 */
  async function handleDetail(record: any) {
    if (record && record.Id) {
      loadingRef.value = true;
      try {
        //TODO:详情表单的弹窗
        detailFormModalMethods.openModal(true, {
          formMode: FormModeEnum.Ok,
          record: record,
        });
      } finally {
        loadingRef.value = false;
      }
    }
  }
  /** 处理编辑 */
  async function handleEdit(record: any) {
    if (record && record.Id) {
      loadingRef.value = true;
      try {
        //TODO:详情表单的弹窗
        detailFormModalMethods.openModal(true, {
          formMode: FormModeEnum.Edit,
          record: record,
        });
      } finally {
        loadingRef.value = false;
      }
    }
  }
  /** 处理详情表单提交后回调，返回true关闭窗体 */
  async function handleAfterDetailSubmit(
    formMode: FormModeEnum,
    result: AjaxResult | null,
    _record: any,
  ) {
    if (result) {
      if (result?.Succeeded) {
        if (result?.Content) {
          createMessage.success(result.Content);
        } else {
          createMessage.success(t('common.successText'));
        }
        switch (formMode) {
          case FormModeEnum.Add:
          case FormModeEnum.Edit:
          case FormModeEnum.Delete:
            await reload();
            break;
        }
        return true;
      } else {
        return false;
      }
    }
    return true;
  }

  /** 处理删除 */
  async function handleDelete(record: any) {
    // console.log('handleDelete', record);
    const ajaxResult = await deleteOrganizations([record.Id]);
    if (ajaxResult.Succeeded) {
      createMessage.success(t('common.successText'));
      await reload();
    }
  }

  //#region "设置组织机构用户-弹窗穿梭框"
  const [registerSetUsersModal, setUsersModalMethods] = useModal();
  /** 处理打开设置组织机构角色弹窗 */
  async function handleSetUsersModalOpen(record: any) {
    if (record && record.Id) {
      const userNodes = await readOrganizationUsers(record.Id);

      setUsersModalMethods.openModal(true, {
        userNodes: userNodes,
        record: record,
      });
      setUsersModalMethods.setModalProps({
        title: `${t('routes.system.identity.user.title')} - ${record.Name}`,
      });
    }
  }
  /** 处理设置组织机构角色弹窗关闭按钮 */
  async function handleSetUsersModalClose() {
    return true;
  }
  /** 处理设置组织机构角色弹窗确定按钮 */
  async function handleSetUsersModalOk(
    targetKeys: (string | bigint)[],
    userNodes: UserOrganizationNode[],
    record: any,
  ) {
    if (targetKeys && userNodes && record && record.Id) {
      const checkedKeys = targetKeys;
      if (checkedKeys) {
        // console.log(checkedKeys);
        const organizationUsers = userNodes
          .filter((item) => item.IsChecked === true)
          .map((item) => {
            return { UserId: item.Id, Administrator: item.Administrator, Leader: item.Leader };
          });
        const ajaxResult = await setOrganizationUsers({
          OrganizationId: record.Id,
          OrganizationUsers: [...organizationUsers],
        });
        if (ajaxResult.Succeeded) {
          createMessage.success(t('common.successText'));
          reload();
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  //#endregion

  //#region "设置组织机构角色-弹窗穿梭框"
  const [registerSetRolesModal, setRolesModalMethods] = useModal();
  /** 处理打开设置组织机构角色弹窗 */
  async function handleSetRolesModalOpen(record: any) {
    if (record && record.Id) {
      const roleNodes = await readOrganizationRoles(record.Id);

      setRolesModalMethods.openModal(true, {
        roleNodes: roleNodes,
        record: record,
      });
      setRolesModalMethods.setModalProps({
        title: `${t('routes.system.identity.role.title')} - ${record.Name}`,
      });
    }
  }
  /** 处理设置组织机构角色弹窗关闭按钮 */
  async function handleSetRolesModalClose() {
    return true;
  }
  /** 处理设置组织机构角色弹窗确定按钮 */
  async function handleSetRolesModalOk(
    targetKeys: (string | bigint)[],
    roleNodes: RoleOrganizationNode[],
    record: any,
  ) {
    if (targetKeys && roleNodes && record && record.Id) {
      const checkedKeys = targetKeys;
      if (checkedKeys) {
        // console.log(checkedKeys);
        const organizationRoles = roleNodes
          .filter((item) => item.IsChecked === true)
          .map((item) => {
            return { RoleId: item.Id, Administrator: item.Administrator, Leader: item.Leader };
          });
        const ajaxResult = await setOrganizationRoles({
          OrganizationId: record.Id,
          OrganizationRoles: [...organizationRoles],
        });
        if (ajaxResult.Succeeded) {
          createMessage.success(t('common.successText'));
          reload();
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  //#endregion
</script>
